var _industry1Dict=['End user','Consultant','Third Organization','System Integrator'],
_industry2Dict=['End user','Consultant','Third Organization'],
_dealerDict=['Distributor'];
avalon.validators.myRequired = {
	// message: 'The other industry is required and must be less than 50 characters long!',
	get: function(value, field, next) {
		if('1'==addPage.forcedCorrelation) {
			if(value ==''){
				next(false);
			} else {
				next(true);
			}
		}else {
			next(true);
		}
		return value
	}
}
avalon.validators.myIndustry1Required={
	get: function(value, field, next) {
		if(_industry1Dict.indexOf(addPage.companyType)!=-1) {
			if(value ==''){
				next(false);
			} else {
				next(true);
			}
		}else {
			next(true);
		}
		return value
	}
}
avalon.validators.myIndustry2Required={
	get: function(value, field, next) {
		if(_industry2Dict.indexOf(addPage.companyType)!=-1) {
			if(value ==''){
				next(false);
			} else {
				next(true);
			}
		}else {
			next(true);
		}
		return value
	}
}
var addPage = avalon.define({
	$id: "addPage",
	uid: "",
	level:'0',
	proxyLevel:'',
	forcedCorrelation:'',
	img1:'',
	imgPath:'',
	parentId:'',
	imgType:'',
	companyType:'',
	distributorList:[],
	industry1:'',
	industry1List:[],
	industry2:'',
	industry2List:[],
	mainMarket:'',
	mailingCountry:'',
	mainMarketList:[],
	validate: {
		onValidateAll: function(reasons) {
			if(reasons.length) {
				// $.openLoadForm($.i18n.prop('contentRefresh'));
				mui.toast(reasons[0].getMessage());
			} else {
				submitIntegralOpen();
			}
		}
	},
	formSubmit: function(e) {
		e.preventDefault()
		this.validate.onManual();
	}
});

mui.ready(function() {
	var uid = $("#uid").val();
	addPage.uid = uid;	

	mui.ajax("/dict/get.json",{
		dataType: 'json',
		type: 'post',
		data: {
			parentId: '0'
		},
		success: function(data) {
			addPage.industry1List=data;
		}
	});	
	mui.ajax("/dict/get.json",{
		dataType: 'json',
		type: 'post',
		data: {
			parentId: '48'
		},
		success: function(data) {
			addPage.mainMarketList=data;
			$('#mainMarket').val(addPage.mainMarket);
		}
	});
	addPage.$watch("industry1", function(a){
		var _val=$('#industry1 option:selected').attr('id');
		if(_val=='') {
			addPage.industry2List=[];
		}else {
			mui.ajax("/dict/get.json",{
				dataType: 'json',
				type: 'post',
				data: {
					parentId: _val
				},
				success: function(data) {
					addPage.industry2List=data;
				}
			});
		}
	});
	mui.ajax("/customer/integral/open/data.json",{
		dataType: 'json',
		type: 'post',
		data: {
			'id':uid
		},
		success: function(data) {
			if('1'==data.status) {
				addPage.level=data.object.level;
				addPage.companyType=data.object.companyType;
				addPage.mainMarket=data.object.countryCode;
				addPage.mailingCountry=data.object.countryCode;
				if('1'==data.object.level) {
					$('#proxyLevelDiv').hide();
					$('#parentIdDiv').hide();
				}else {
					addPage.forcedCorrelation=data.object.forcedCorrelation;
					addPage.distributorList=data.object.distributor;
				}
				if(_dealerDict.indexOf(data.object.addPage)==-1){
					addPage.proxyLevel='1';
				}
				initRequired();
				i18nReady();
			}
		}
	});
	
	// $('#industry1').on('change', function(){
	// 	var _val=$(this).val();
	// 	if(_val=='') {
	// 		addPage.industry2List=[];
	// 	}else {
	// 		mui.ajax("/dict/get.json",{
	// 			dataType: 'json',
	// 			type: 'post',
	// 			data: {
	// 				parentId: _val
	// 			},
	// 			success: function(data) {
	// 				addPage.industry2List=data;
	// 			}
	// 		});
	// 	}
	// });
	// mui(".upload").on('tap','a',function(){
	// 	// var imgAttr=addPage.imgType;
	// 	// $('#uploadImg').attr('data-type',imgAttr);
	// 	$('#uploadImg').click();
	// });
	$('#uploadImg').on('change', function(e){
		var self=this;
		var $target=e.target||e.srcElement;
		var file=$target.files[0], Orientation;
		
		if(!file||!window.FileReader) return;
		$.openLoadForm($.i18n.prop('contentRefresh'));
		if(/^image/.test(file.type)) {
			var reader=new FileReader();
			reader.readAsDataURL(file);
			reader.onloadend=function(){
				// if(this.result.length<=(3*1024*1024)) {
					addPage.img1=this.result;
					postImg(this.result, file);
				// }else {
				// }
			};
		}
	});

	function postImg(result, file) {
		var self=this, paramObj={}, size=result.length;
		paramObj.extName=file.type.replace('image/','');
		paramObj.size=size;
		paramObj.type='integral';
		paramObj.fileName=$('#uploadImg').attr('data-type');
		console.log(paramObj);
		paramObj.imgFile=result;
		mui.ajax('/tools/base64.json', {
			data: paramObj,
			type:'post',
			dataType: 'json',
			success: function(data) {
				console.log(data);
				if(data.status==1) {
					// mui.confirm("是否提交上传附件？", '提示', ['取消','上传并提交'], function(e) {
					// 	if(e.index == 1) {
					// 		submitIntegralOpen(data);
					// 	}
					// });
					addPage.imgPath=data.object;
					$('#img').attr('src',result);
					$.closeLoadForm();
				}else {
					
				}
			}
		});
	}

// 	$("#locations").cxSelect({
// 		selects: ["region", "country", "state"],
// 		required:false,
// 		firstTitle:"Please select"
// 	});
// 
// 	mui(".header").on('tap', '.login', function() {
// 		var url = "dahua://nativeback";
// 		mui.openWindow({
// 			url: url
// 		});
// 	});
// 
// 	mui(".header").on('tap', '.home', function() {
// 		var url = this.getAttribute('href');
// 		mui.openWindow({
// 			url: url
// 		});
// 
// 	});
// //    mui(".mui-scroll").on('tap', 'a', function() {
// //         var url = this.getAttribute('href');
// //                          console.log(mui.plus);
// //         var w = mui.plus.webview.create(url);
// //         w.show(); // 显示窗口
// //
// ////         mui.openWindow({
// ////             url: url
// ////          });ßß
// //    });
// 
// //    mui(".mui-content").on('tap', '#cookieStatementShow', function() {
// //         location.href="#cookieStatement";
// //         });
//     /*mui(".mui-row").on('tap', '#showStatement', function() {
//         $("#regPage").addClass("mui-hidden");
//         $("#statementPage").removeClass("mui-hidden");
//     });*/
//   var CX;
// 	mui(".mui-row").on('tap', '#showPrivacy', function() {
// 		$("#regPage").addClass("mui-hidden");
// 		$("#privacyText").removeClass("mui-hidden");
//        CX = $('#cookieStatement').offset().top;
// 	});
// 	
// 	mui(".mui-row").on('tap', '#showTerms', function() {
// 		$("#regPage").addClass("mui-hidden");
// 		$("#termsText").removeClass("mui-hidden");
// 	});
// 	
// 	mui(".header").on('tap', '#backReg', function() {
// 		$("#statementPage").addClass("mui-hidden");
// 		$("#privacyText").addClass("mui-hidden");
// 		$("#termsText").addClass("mui-hidden");
// 		$("#regPage").removeClass("mui-hidden");
// 	});
// 
//     mui(".mui-row").on('tap', '#windowslocatinHtml', function() {
//         var url = this.getAttribute('href');
//          location.href = "dahua://openweb?" + url;
//     });
//           
//   mui(".mui-row").on('tap', '#cookieStatementShow', function() {
//          $('#cookieStatementShow').offset().top;
//          mui("#privacyText_scroll").scroll().scrollTo(0,-CX+40);
//  });
});

function submitIntegralOpen(){
	$.openLoadForm($.i18n.prop('contentRefresh'));
	var impType = addPage.imgType;
	var param={
		"target.id":addPage.uid,
		"industry1":addPage.industry1,
		"industry2":addPage.industry2,
		"market":addPage.mainMarket,
		"mailingCountry":addPage.mailingCountry
	};
	if(impType=='1') {
		param.businessLicenseImg='/'+addPage.imgPath;
	}else if(impType=='2'){
		param.storeImg='/'+addPage.imgPath;
	}else if(impType=='3'){
		param.businessCardImg='/'+addPage.imgPath;
	}
	if(addPage.level=='0') {
		if(addPage.parentId!='') {
			param['target.parentId']=addPage.parentId;
			param['target.level']='2'
		}else if(addPage.proxyLevel=='1'){
			param['target.level']='2'
		}
	}
	mui.ajax('/customer/integral/open.do', {
		data: param,
		type:'post',
		dataType: 'json',
		success: function(data) {
			$.closeLoadForm();
			if(data.status==1) {
				mui.alert($.i18n.prop('Scan_message8'), "", "ok", function(e) {
					var url = "../partner/index.html";
					mui.openWindow({
						url: url
					});
				});
			}else if(data.status==2){
				mui.alert($.i18n.prop('Scan_message10'));
			}
		}
	});
}
function initRequired(){
	if('1'==addPage.forcedCorrelation) {
		$('#parentIdDiv h5').prepend('<sup>*</sup>');
	}
	if(_industry1Dict.indexOf(addPage.companyType)!=-1) {
		$('#industryIDiv h5').prepend('<sup>*</sup>');
	}
	if(_industry2Dict.indexOf(addPage.companyType)!=-1){
		$('#industryIIDiv h5').prepend('<sup>*</sup>');
	}
}